package com.chenjj.java.mq.rabbitmq;

import cn.hutool.json.JSONUtil;
import com.chenjj.java.business.order.OrderInfoVO;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;

/**
 * 简单的消息生产者
 */
public class OrderProviderSimple {
    private Logger logger = LoggerFactory.getLogger(OrderProviderSimple.class);

    private String defaultUri = "amqp://cjj:cjj@localhost:5672/vhost_cjj";

    private ConnectionFactory connectionFactory = new ConnectionFactory();

    public OrderProviderSimple() throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException {
        connectionFactory.setUri(defaultUri);
    }

    public OrderProviderSimple(String uri) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException {
        connectionFactory.setUri(uri);
    }

    /**
     * 将orderInfo 发送到MQ
     * @param orderInfoVO
     */
    public void sendOrderInfo(OrderInfoVO orderInfoVO){
        String queueName = "orderInfoQueue";


        Connection connection = null;
        Channel channel = null;
        try{
            String orderInfoStr = JSONUtil.parse(orderInfoVO).toString();
            byte [] orderInfoByte = orderInfoStr.getBytes("UTF-8");

            System.out.println("Publish message: " + orderInfoStr);

            connection = connectionFactory.newConnection();
            channel = connection.createChannel();
            //声明一个队列， 队列名："", 持久的：false,独占的： true,是否自动删除 true,其他参数 null
            //channel.queueDeclare();
            //声明一个队列，队列名：queueName, 持久的：true,独占的(设置成false才能在admin页面看到)： false,是否自动删除 false,其他参数 null
            //channel.queueDeclare(queueName,true,false,false,null);
            //发布消息(持久化消息)
            //channel.basicPublish("",queueName,MessageProperties.PERSISTENT_TEXT_PLAIN,orderInfoByte);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("",e);
        }finally {
            releaseResource(connection,channel);
        }
    }

    private void releaseResource(Connection connection,Channel channel){
//        if (channel!=null){
//            try {
//                channel.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            } catch (TimeoutException e) {
//                e.printStackTrace();
//            }
//        }
//        if(connection!=null){
//            try {
//                connection.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
    }
}
